<?php
namespace App\Admin\Repositories;

use App\Models\WxMenu as Model;
use Dcat\Admin\Repositories\EloquentRepository;
class WxMenu extends EloquentRepository
{
    /**
     * Model.
     *
     * @var string
     */
    protected $eloquentClass = Model::class;

    public static function get_menus($id, $need_child = true){

        if(_empty_($id) || !is_numeric($id)){
            return [];
        }
        $parent_menus = [];
        $root_menu = null;
        // 一级菜单
        Model::select('id', 'title','icon','url')->where('parent_id', $id)->orwhere('id', $id)->orderBy('order', 'asc')->get()->each(function ($value, $key) use (&$parent_menus, $id, &$root_menu){
            if($value->id == $id){
                $root_menu = ['id'=>$id, 'title'=>$value->title, 'icon'=>($value->icon ? '<i class="fa '.$value->icon.'"></i>' : ''), 'url'=>$value->url, 'sub'=>[]];
            }else{
                $parent_menus[$value->id] = ['id'=>$value->id, 'title'=>$value->title, 'icon'=>($value->icon ? '<i class="fa '.$value->icon.'"></i>' : ''), 'url'=>$value->url, 'sub'=>[]];
            }
        });

        if(_empty_($parent_menus)){
            return [];
        }

        if($need_child){
            Model::select('title','icon','url', 'parent_id')->whereIn('parent_id', array_keys($parent_menus))->get()->each(function ($value, $key) use (&$parent_menus){
                $parent_menus[$value->parent_id]['sub'][] = ['id'=>$value->id, 'title'=>$value->title, 'icon'=>($value->icon ? '<i class="fa '.$value->icon.'"></i>' : ''), 'url'=>$value->url, 'sub'=>[]];
            });
        }

        $parent_menus[$id] = $root_menu;
        return $parent_menus;

    }


}
